<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户展示</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 30px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="username4search"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="realName4search"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增，发布任务 -->
      <el-row>
        <el-button :disabled="isAllDel" type="danger" plain @click="toggleSelection">批量删除</el-button>
      </el-row>
    </div>
    <!-- 分页数据展示 -->
    <div style="background-color: white; border-radius: 2px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
      <el-table
        ref="multipleTable"
        v-loading="isLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        style="width: 100%; margin-top: 10px;"
        max-height="400"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column
          fixed
          prop="username"
          label="用户名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="realName"
          label="用户真实姓名"
          width="200">
        </el-table-column>
        <el-table-column
          prop="tel"
          label="联系电话"
          width="200">
        </el-table-column>
        <el-table-column
          prop="qq"
          label="用户qq"
          width="200">
        </el-table-column>
        <el-table-column
          prop="role"
          label="角色"
          width="200">
        </el-table-column>
        <el-table-column
          prop="reputation"
          label="信誉分"
          width="200">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="内容"
          width="600">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="edit(scope.$index, tableData)"
              type="text"
              size="small">
              编辑
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              type="text"
              size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </div>
    <el-dialog v-dialog-drag title="信息编辑" :visible.sync="dialogFormVisible">
      <div>
        <el-form :model="userData" ref="userForm" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input clearable="clearable" v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName" required>
            <el-input clearable="clearable" v-model="userData.realName"></el-input>
          </el-form-item>
          <el-form-item label="您的联系电话" prop="tel">
            <el-input type="number" clearable="clearable" v-model="userData.tel"></el-input>
          </el-form-item>
          <el-form-item label="您的联系QQ" prop="qq">
            <el-input type="number" clearable="clearable" v-model="userData.qq"></el-input>
          </el-form-item>
          <el-form-item label="您的寝室" prop="bedroomAddr" required>
            <el-input clearable="clearable" v-model="userData.bedroomAddr"></el-input>
          </el-form-item>
          <el-form-item label="介绍" prop="remark">
            <el-input type="textarea" v-model="userData.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import loading from "@/components/loading";
import {list, del, search} from "@/api/user";
import store from "@/store";

export default {
  inject: ['reload'],
  name: "allUsers",
  components: { loading },
  mounted() {
    this.isLoading = true
    this.userList()
  },
  methods: {

    async search(){
      this.tableData = []
      const response = await search({username: this.username4search, realName: this.realName4search})
      console.log('query user: ',response)
      this.tableData = response.data.data.list
      this.$notify({
        title: '成功',
        message: '查询成功，刷新看一看叭。',
        type:'success'
      })
    },

    async userList() {
      this.isLoading = false
      const response = await list(this.pageNum, this.pageSize)
      console.log('this the user：',response)
      this.pageNum = response.data.pageNum
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      this.tableData = response.data.list
    },
    onSubmit() {
      console.log('submit!');
    },
    edit(index, rows){
      this.userData = rows[index]
      this.dialogFormVisible=true
    },
    deleteRow(index, rows) {
      console.log('我删除某条信息')
      console.log(index, rows)
      // rows.splice(index, 1);
    },
    // 时间戳转换成时间
// 使用element table组件中的formatter属性，传入一个函数
    timestampToTime (row, column) {
      var date = new Date(row[column.property]) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    async handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.isLoading = true
      const response = await list(this.pageNum, val)
      this.pageNum = response.data.pageNum
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      await this.userList()
    },
    async handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.isLoading = true
      const response = await list(val, this.pageSize)
      this.pageNum = val
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      await this.userList()
    },
    async toggleSelection() {
      const vals = this.delIds
      for (let i = 0; i < vals.length; i++) {
        console.log('del;',vals[i])
        await del(vals[i])
      }
      this.$notify({
        title: '成功',
        message: '删除成功，请刷新看一看叭。',
        type:'success'
      })
      this.reload()
    },
    handleSelectionChange(val) {
      if (val.length > 0){
        this.isAllDel = !this.isAllDel
        console.log(val)
        this.multipleSelection = val;
      }else{
        this.isAllDel = true
      }
      for (let i = 0; i < val.length; i++) {
        this.delIds.push(val[i].id)
      }
    },
    async submitForm() {
      await this.$refs.userForm.validate((valid) => {
        if (valid) {
          // get user
          store.dispatch('user/getInfo').then(data => {
            //
            data = this.userData
            console.log({id: data.id, data: this.userData})
            this.$store.dispatch('user/update', {id: data.id, data: this.userData})
              .then(() => {
                this.dialogFormVisible = false
                this.$router.push('/main/users')
              })
              .catch(() => {
                this.loading = false
              })
          })
        } else {
          return false;
        }
      });
    },
  },
  data() {
    return {
      //
      delIds: [],
      isAllDel: true,
      username4search: '',
      realName4search: '',
      // task
      pageNum: 1,
      pageSize: 5,
      pageTotal: 5,
      userForm: {
        bedroomAddr: "",
        qq: 2538684421,
        realName: '',
        remark: "",
        reputation: 100,
        role: "-",
        tel: 13900000000,
        username: "-",
      },
      userData: {
        bedroomAddr: "",
        qq: '',
        realName: '',
        remark: "",
        reputation: 100,
        role: "-",
        tel: 13900000000,
        username: "-",
      },
      //
      dialogTableVisible: false,
      dialogFormVisible: false,
      // ++++++++++++++++++++++++
      multipleSelection: [],
      isLoading: false,
      tableData: [],
    }
  }
}
</script>

<style scoped>

</style>
